package com.jzit168.module_main.ui.main

import android.os.Bundle
import androidx.viewpager2.widget.ViewPager2
import com.alibaba.android.arouter.facade.annotation.Route
import com.jzit168.library_arouter.ARouterConstant
import com.jzit168.library_arouter.getFragment
import com.jzit168.library_base.baseVBVM.BaseVBVMActivity
import com.jzit168.module_main.R
import com.jzit168.module_main.databinding.ActivityMainBinding

/**
 * @Desc: 装载碎片切换的界面
 * @Author: lx
 * @Date: 2020/10/20
 *
 */
@Route(path = ARouterConstant.Main.toMainActivity)
class MainActivity : BaseVBVMActivity<ActivityMainBinding, MainViewModel>() {

    private val switchAdapter by lazy { SwitchAdapter(supportFragmentManager, lifecycle) }

    override fun getViewBinding(): ActivityMainBinding = ActivityMainBinding.inflate(layoutInflater)

    override fun getViewModel(): Class<MainViewModel> = MainViewModel::class.java

    override fun initView(savedInstanceState: Bundle?) {
        super.initView(savedInstanceState)
        initVpAndBottomNav()
    }

    private fun initVpAndBottomNav() {
        switchAdapter.also {
            it.addFragment(getFragment(ARouterConstant.Home.toHomeFragment))
            it.addFragment(getFragment(ARouterConstant.Devices.toDevicesFragment))
            it.addFragment(getFragment(ARouterConstant.User.toMineFragment))
        }
        binding.apply {
            viewpager2.apply {
                adapter = switchAdapter
                isUserInputEnabled = false
                registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
                    override fun onPageSelected(position: Int) {
                        super.onPageSelected(position)
                        bottomNav.menu.getItem(position).isChecked = true
                    }
                })
            }
            bottomNav.setOnNavigationItemSelectedListener {
                when (it.itemId) {
                    R.id.home -> {
                        viewpager2.setCurrentItem(0, false)
                    }
                    R.id.devices -> {
                        viewpager2.setCurrentItem(1, false)
                    }
                    R.id.mine -> {
                        viewpager2.setCurrentItem(2, false)
                    }
                }
                true
            }

        }
    }
}